/********************************************************************************
 *@description: 
 *@author: Xhd
 *@API: 
 *@Product: 
 *@date: 2024-05-07 10:49:16
 *@version: V1.0.0
**********************************************************************************/

import React, { Component } from 'react';
import { Form, Button, Input, InputNumber, Space } from 'antd';
import { apiGetQuestionTypeAddOrUpdate } from "@/request/app/questions";

class AddOrEdit extends Component {
  constructor(props) {
    super(props)
    this.formRef = React.createRef();
    this.state = {
      type: '',
      tips: '',
      initialValue: {}
    }
  }
  componentDidMount() {
    let data = this.props.data
    let tips
    if (data.aeType === "add") {
      tips = "创建完成后，默认停用状态，启用后APP端显示该类目。"
      this.formRef.setFieldsValue({})
    } else {
      tips = "修改完成后，APP端同步更新"
      this.formRef.setFieldsValue(data.info)
    }
    this.setState({
      tips,
      initialValue: data.info,
      type: data.aeType
    })
  }

  // 点击取消
  onCancel = () => {
    this.props.onCancel()
  }

  // 点击确定
  submit = async (values) => {
    const { type, initialValue } = this.state
    if (type === "add") {
      await apiGetQuestionTypeAddOrUpdate(values).then(res => {
        if (res.code === 0) {
          React.$message({
            type: 'success',
            content: '新增成功'
          })
          this.onCancel()
          this.props.onOk()
        }
      })
    } else {
      await apiGetQuestionTypeAddOrUpdate({ typeId: initialValue.typeId, ...values }).then(res => {
        if (res.code === 0) {
          React.$message({
            type: 'success',
            content: '修改成功'
          })
          this.onCancel()
          this.props.onOk()
        }
      })
    }
  }

  render() {
    const { tips, initialValue } = this.state;
    return (<Form ref={ref => this.formRef = ref}
      initialValues={initialValue} layout={"vertical"} onFinish={(values) => this.submit(values)}
    >
      <Form.Item label="类型名称：" name={"typeName"} rules={[{ required: true, message: '请输入' }]} >
        <Input placeholder='请输入' maxLength={6} showCount />
      </Form.Item>
      <Form.Item label="排序：" name={"sort"} rules={[{ required: true, message: '请输入' }]} >
        <InputNumber placeholder='请输入排序数字（字数越小越靠前，0最小）' min={0} controls={false} precision={0} />
      </Form.Item>
      <Form.Item>
        温馨提示：{tips}
      </Form.Item>
      <Form.Item wrapperCol={{
        offset: 8,
        span: 16,
      }}>
        <Space>
          <Button onClick={() => this.onCancel()} >取消</Button>
          <Button type='primary' htmlType='submit' >确定</Button>
        </Space>
      </Form.Item>
    </Form>)
  }
}

export default AddOrEdit